<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>界面与数据分离</title>
</head>
<body>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
    <script>
        $(function () {
            var Countries = function () { }

            Countries.prototype = {
                _items: [],
                _getData: function (success) {
                    var items = [
                        { id: 0, name: '中国' },
                        { id: 1, name: '日本' },
                        { id: 2, name: '美国' }
                    ];
                    $.extend(this._items, items);
                    success(items);
                },
                //Events
                on_selected: $.Callbacks(),
                on_inserted: $.Callbacks(),
                //Methods
                select: function () {
                    var self = this;
                    this._getData(function (items) {
                        self.on_selected.fire({
                            sender: self,
                            items: items
                        });
                    });
                },
                insert: function (item) {
                    var self = this;
                    this._items.push(item);
                    self.on_inserted.fire({ sender: self, item: item });
                }
            }

            //=======================================================================
            // 以下为界面代码，当要调整界面，改这里就行啦~~~
            var countries = new Countries();
            countries.on_selected.add(function (args) {
                $(args.items).each(function () {
                    $('#countries').append($('<option>').attr('value', this.id).text(this.name));
                });
            });

            countries.on_inserted.add(function (args) {
                $('#countries').append($('<option selected="selected">').attr('value', args.item.id).text(args.item.name));
            });

            var id = 10;
            $('#btnAdd').click(function () {
                countries.insert({ id: ++id, name: $('#countryName').val() });
            });

            countries.select();
            //=======================================================================
        });

    </script>
</head>
<body>
<select id="countries"></select>
<div>
    <input id="countryName" /><button id="btnAdd">添加</button>
</div>
</body>
</html>
</body>
</html>